from django.db import transaction
from django.shortcuts import redirect,render
from web import models
from utils.group import NbSearchGroup
from utils.pager import Pagination
from utils.video import *
from django.core.exceptions import ValidationError
from django import forms
from utils.bootstrap import BootStrapForm
import random
import datetime
from django.db.models import F
from django_redis import get_redis_connection
from django.conf import settings
from django.contrib import messages

def my_order_list(request):
    queryset = models.Order.objects.filter(customer_id=request.fc_user.id).order_by("-id")
    pager = Pagination(request, queryset)
    return render(request, "my_order_list.html", {"pager": pager})

class MyOrderAddForm(BootStrapForm,forms.ModelForm):
    class Meta:
        model = models.Order
        fields = ['url','count']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        price_count_list = []
        text_count_list = []
        queryset = models.PricePolicy.objects.all().order_by("count")
        for item in queryset:
            unit_price = item.price / item.count
            price_count_list.append([item.count, f'>={item.count}条的价格是{unit_price}', unit_price])
            text_count_list.append(f'>={item.count}条的价格是{unit_price}')

        if text_count_list:
            self.fields['count'].help_text = ",".join(text_count_list)
        else:
            self.fields['count'].help_text = "请联系管理员设置价格"

        self.price_count_list = price_count_list

    def clean_count(self):
        count = self.cleaned_data['count']
        if not self.price_count_list:
            raise ValidationError('请联系管理员设置价格')

        if count < self.price_count_list[0][0]:
            raise ValidationError(f"最少数量不少于{self.price_count_list[0][0]}")

        return count
def my_order_add(request):
    if request.method == "GET":
        form  = MyOrderAddForm()
        return render(request,'form.html',{'form':form})
    form = MyOrderAddForm(request.POST)
    if not form.is_valid():
        return render(request,'form.html',{'form':form})
    video_url = form.cleaned_data['url']
    count = form.cleaned_data['count']
    status,old_view_count = get_old_view_count(video_url)
    if not status:
        form.add_error('url','视频地址获取失败')
        return render(request,'form.html',{'form':form})

    for i in range(len(form.price_count_list)-1,-1,-1):
        limit_price,_,unit_price = form.price_count_list[i]
        if limit_price < count:
            break
    total_price = count * unit_price

    try:
        with transaction.atomic():
            customer_obj = models.Customer.objects.filter(id=request.fc_user.id).select_for_update().first()
            real_price = total_price * customer_obj.level.percent/100

            if total_price < real_price:
                form.add_error('count','账户余额不足')
                return render(request,'form.html',{'form':form})

            while True:
                num = random.randint(100000,999999)
                id_time = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
                oid = f'{id_time}{num}'
                exist = models.Order.objects.filter(oid=oid).exists()
                if exist:
                    continue
                break

            form.instance.oid = oid
            form.instance.price = total_price
            form.instance.real_price = real_price
            form.instance.old_view_count = old_view_count
            form.instance.customer_id = request.fc_user.id
            form.save()

            models.Customer.objects.filter(id=request.fc_user.id).update(balance=F('balance') - real_price)
            # cus_object.balance = cus_object.balance - real_price
            # cus_object.save()

            models.TransactionRecord.objects.create(
                charge_type=3,
                customer_id=request.fc_user.id,
                amount=real_price,
                order_oid=oid,
            )

            conn = get_redis_connection('default')
            conn.lpush(settings.QUEUE_TASK_NAME, oid)

    except Exception as e:
        print(e)
        form.add_error('count','创建订单失败')
        return render(request,'form.html',{'form':form})
    return redirect('my_order_list')


def my_order_cancel(request,pk):
    order_obj = models.Order.objects.filter(customer=request.fc_user.id,active=1,status=1,id=pk).first()
    if not order_obj:
         messages.add_message(request,settings.MESSAGE_DANDER_TAG,'订单不存在')
         return redirect('my_order_list')

    try:
        with transaction.atomic():
            models.Customer.objects.filter(id=request.fc_user.id).select_for_update().first()

            models.Order.objects.filter(id=pk,status=1,active=1,customer=request.fc_user.id).update(status=5)

            models.Customer.objects.filter(id=request.fc_user.id).update(balance=F('balance') + order_obj.real_price)

            models.TransactionRecord.objects.create(
                charge_type=5,
                customer_id=request.fc_user.id,
                amount=order_obj.real_price,
                order_oid=order_obj.oid,
            )

            messages.add_message(request,settings.MESSAGE_DANDER_TAG,'撤单成功')
            return redirect('my_order_list')
    except Exception as e:
        messages.add_message(request,settings.MESSAGE_DANDER_TAG,f"撤单失败，{str(e)}")
        return redirect('my_order_list')
